﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FisheryPlatform.Search.Core.Analysis
{
    /// <summary>			
    /// Filter
    /// description:	过滤器
    /// create date:	2006-05
    /// author:			gwd
    /// </summary>
    public abstract class Filter
    {

        protected internal System.Collections.Hashtable _items = null;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="fullPath"></param>
        public Filter(string name, string fullPath)
        {
            _name = name.ToLower();
            _fullPath = fullPath;
        }

        public string Name
        {
            get { return _name; }
        }
        private string _name;

        public string FullPath
        {
            get { return _fullPath; }
        }
        private string _fullPath;

        protected internal virtual void LoadFilter()
        {
            _items = new System.Collections.Hashtable();

            System.IO.StreamReader reader = null;
            try
            {
                reader = new System.IO.StreamReader(_fullPath, MMSupport.GetEncoding());
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    int pos = line.LastIndexOf("||");
                    if (pos <= -1)
                    {
                        if (line == "\\n")
                            line = "\n";
                        else if (line == "\\r")
                            line = "\r";
                        _items.Add(line, string.Empty.PadLeft(line.Length, ' '));
                    }
                    else
                    {
                        string strPre = line.Substring(0, pos);
                        // ## Translate Escape character
                        if (strPre == "\\n")
                            strPre = "\n";
                        else if (strPre == "\\r")
                            strPre = "\r";
                        _items.Add(strPre, line.Substring(pos + 2));
                    }
                }
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }

        public virtual bool Lookup(string key)
        {
            if (_items == null) return false;

            return _items.ContainsKey(key);
        }

        public virtual string GetItem(string key)
        {
            if (_items == null) return null;

            if (this.Lookup(key)) return _items[key].ToString();
            else return null;
        }

        public abstract string Execute(string key);

    }
}
